package com.lamp.main;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.c2dm.C2DMessaging;
import com.lamp.JsonClass.FriendList;
import com.lamp.JsonClass.FriendStatus;
import com.lamp.JsonClass.MessageList;
import com.lamp.JsonClass.MessageListStatus;
import com.lamp.JsonClass.UserInfo;
import com.lamp.connection.HttpConnectionManager;
import com.lamp.connection.OnHttpConnectionLoad;
import com.lamp.date.DateEpoch;

public class LoginActivity extends Activity implements LocationListener {
	/** Called when the activity is first created. */

	public View eventView = null;

	public static String Token = null;
	public static int statuscode = -1;
	public static int userId;
	public static int BusinessId;
	public static String userPhoto;
	public static String userName;
	public static Resources resource;
	public static LoginActivity lampLogin;

	private UserInfo userInfo;
	private FriendStatus friendStatus;
	private FriendStatus newFriendStatus;
	private MessageListStatus messageListStatus;
	private List<String> sendRequested;
	private int newMessageTotal;
	public int requestTotal = 0;
	public Location currentLocation;

	HttpConnectionManager manager;

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		overridePendingTransition(R.anim.alpha, R.anim.alpha1);
	}

	Button b1;
	EditText email;
	EditText password;
	String loginStr;
	String passStr;
	List<NameValuePair> params;
	private ProgressDialog dialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		String registrationID = C2DMessaging.getRegistrationId(this);
		Log.w("C2DM_REGISTRATION_ID", registrationID);
		if (registrationID == null || registrationID.length() == 0) {
			C2DMessaging.register(this, "samun.auro@gmail.com");
		}
 
		manager = new HttpConnectionManager();
		params = new ArrayList<NameValuePair>();
		sendRequested = new ArrayList<String>();
		Criteria locCriteria = new Criteria();
		locCriteria.setAccuracy(Criteria.ACCURACY_FINE);
		LocationManager locMan = (LocationManager) getSystemService(LOCATION_SERVICE);
		locMan.requestLocationUpdates(
				locMan.getBestProvider(locCriteria, true), 2000, 25, this);

		currentLocation = locMan.getLastKnownLocation(locMan.getBestProvider(
				locCriteria, true));

		lampLogin = this;
		email = (EditText) findViewById(R.id.email_edt);
		password = (EditText) findViewById(R.id.password_edt);
		email.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// If the event is a key-down event on the "enter" button
				if ((event.getAction() == KeyEvent.ACTION_DOWN)
						&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
					String k = email.getText().toString();
					if (k.length() > 0) {
						password.requestFocus();
					}
					return true;
				}
				return false;
			}
		});
		password.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// If the event is a key-down event on the "enter" button
				if ((event.getAction() == KeyEvent.ACTION_DOWN)
						&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
					request();
				}
				return false;
			}
		});

		resource = getResources();

	}

	public void request() {
		loginStr = email.getText().toString();
		passStr = password.getText().toString();
		password.setText("");
		if (loginStr.length() > 0 && passStr.length() > 0) {

			params.add(new BasicNameValuePair("Email", loginStr));
			params.add(new BasicNameValuePair("Password", passStr));
			Log.v("Login", "Request");
			dialog = new ProgressDialog(this) {
				@Override
				public boolean onKeyDown(int keyCode, KeyEvent event) {
					if (keyCode == KeyEvent.KEYCODE_BACK) {
						dialog.dismiss();
						manager.abordRequest();
						return true;
					}
					return super.onKeyDown(keyCode, event);
				}
			};
			dialog.setMessage("Check username password");
			dialog.setTitle("Login");
			dialog.show();
			manager.sentRequest(
					"http://www.lamp.mn/lamp/webservices/lampLogin.php",
					params, new OnHttpConnectionLoad() {

						public void onHttpConnectionExecuted(String response) {
							// TODO Auto-generated method stub
							Log.d("RESPONSE", response);
							int statusCode = 0;
							try {
								JSONObject json = new JSONObject(response);
								statusCode = json.getInt("StatusCode");
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							if (statusCode == 0) {

								JSONObject login;
								try {
									login = new JSONObject(response);
									LoginActivity.Token = login
											.getString("Token");
									LoginActivity.userId = login
											.getInt("UserId");
									LoginActivity.BusinessId = login
											.getInt("BusinessId");

									userRequest();
								} catch (JSONException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

							} else {
								Toast.makeText(LoginActivity.this,
										"Invalid Login or Password",
										Toast.LENGTH_SHORT).show();
							}

						}

						public void onHttpConnectionFailed() {
							dialog.dismiss();
						}
					});
		}
	}

	public void addRequest(String userId) {
		sendRequested.add(userId);
	}

	public void setNewMessageTotal(int newMessageTotal) {
		this.newMessageTotal = newMessageTotal;
	}

	public int getNewMessageTotal() {
		return this.newMessageTotal;
	}

	public void setUserInfo(UserInfo userInfo) {
		this.userInfo = userInfo;
	}

	public UserInfo getUserInfo() {
		return this.userInfo;
	}

	public FriendStatus getNewFriendStatus() {
		return this.newFriendStatus;
	}

	public void setNewFriendStatus(FriendStatus friendStatus) {
		this.newFriendStatus = friendStatus;
	}

	public FriendStatus getFriendStatus() {
		return this.friendStatus;
	}

	public void setFriendStatus(FriendStatus friendStatus) {
		this.friendStatus = friendStatus;
	}

	public MessageListStatus getMessageListStatus() {
		return this.messageListStatus;
	}

	public void setMessageListStatus(MessageListStatus messageListStatus) {
		this.messageListStatus = messageListStatus;
	}

	public String getPassword() {
		return passStr;
	}

	public void userRequest() {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("Token", LoginActivity.Token));
		params.add(new BasicNameValuePair("UserId", Integer
				.toString(LoginActivity.userId)));
		manager.sentRequest("http://www.lamp.mn/lamp/webservices/getUser.php",
				params, new OnHttpConnectionLoad() {

					@Override
					public void onHttpConnectionFailed() {
						// TODO Auto-generated method stub

					}

					@Override
					public void onHttpConnectionExecuted(String response) {
						userInfo = new UserInfo();
						Log.v("LoginActivity", "GETUSER");
						try {
							JSONObject JsonUserInfo = new JSONObject(response);
							userInfo.setStatusCode(JsonUserInfo
									.getInt("StatusCode"));
							userInfo.setEmailAddress(JsonUserInfo
									.getString("EmailAddress"));
							userInfo.setFirstName(JsonUserInfo
									.getString("FirstName"));
							userInfo.setLastName(JsonUserInfo
									.getString("LastName"));
							userInfo.setPhone(JsonUserInfo.getString("Phone"));
							userInfo.setAddress(JsonUserInfo
									.getString("Address"));
							userInfo.setGender(JsonUserInfo.getString("Gender"));
							if (!JsonUserInfo.isNull("Birthday")
									&& !JsonUserInfo.getString("Birthday")
											.equals(""))
								userInfo.setBirthday(JsonUserInfo
										.getString("Birthday"));
							userInfo.setPhoto(JsonUserInfo.getString("Photo"));
							userInfo.setTwitterURL(JsonUserInfo
									.getString("TwitterURL"));
							userInfo.setFacebookURL(JsonUserInfo
									.getString("FacebookURL"));
							userInfo.setFriend(JsonUserInfo.getString("Friend"));
							if (!JsonUserInfo.isNull("BusinessId")
									&& !JsonUserInfo.getString("BusinessId")
											.equals(""))
								userInfo.setBusinessId(JsonUserInfo
										.getInt("BusinessId"));
							userInfo.setLastSeen(JsonUserInfo
									.getString("LastSeen"));
							userInfo.setLastSeenTime(JsonUserInfo
									.getString("LastSeenTime"));
							if (!JsonUserInfo.isNull("LastSeenId")
									&& !JsonUserInfo.getString("LastSeenId")
											.equals(""))
								userInfo.setLastSeenId(JsonUserInfo
										.getInt("LastSeenId"));
							userInfo.setScore(JsonUserInfo.getInt("Score"));
							userInfo.setKingCount(JsonUserInfo
									.getInt("KingCount"));

						} catch (JSONException e1) {
							e1.printStackTrace();
						}
					}
				});

		List<NameValuePair> params1 = new ArrayList<NameValuePair>();
		params1.add(new BasicNameValuePair("Token", LoginActivity.Token));
		params1.add(new BasicNameValuePair("Skip", Integer.toString(0)));
		params1.add(new BasicNameValuePair("Take", Integer.toString(20)));
		// 47.919878, 106.930042
		manager.sentRequest(
				"http://www.lamp.mn/lamp/webservices/getFriendReqLists.php",
				params1, new OnHttpConnectionLoad() {

					@Override
					public void onHttpConnectionFailed() {
						// TODO Auto-generated method stub

					}

					@Override
					public void onHttpConnectionExecuted(String response) {
						final FriendStatus friendStatusR = new FriendStatus();
						final List<FriendList> friendListR = new ArrayList<FriendList>();

						Log.v("LoginActivity", "GETFRIENDREQLIST");
						try {
							JSONObject JsonFriendListStatus = new JSONObject(
									response);
							friendStatusR.setStatusCode(JsonFriendListStatus
									.getInt("StatusCode"));
							friendStatusR.setTotal(JsonFriendListStatus
									.getInt("Total"));
							JSONArray JsonFriendList = JsonFriendListStatus
									.getJSONArray("FriendList");
							for (int i = 0; i < JsonFriendList.length(); i++) {
								FriendList friendListItem = new FriendList();
								friendListItem.setFriendId(JsonFriendList
										.getJSONObject(i).getInt("FriendId"));
								friendListItem.setUserId(JsonFriendList
										.getJSONObject(i).getInt("UserId"));
								friendListItem
										.setUserName(JsonFriendList
												.getJSONObject(i).getString(
														"UserName"));

								friendListItem.setPhoto(JsonFriendList
										.getJSONObject(i).getString("Photo"));
								friendListItem.setMutualFriend(JsonFriendList
										.getJSONObject(i)
										.getInt("MutualFriend"));
								friendListItem.setLoggedAt(new DateEpoch(
										JsonFriendList.getJSONObject(i)
												.getString("LoggedAt")));
								if (!JsonFriendList.getJSONObject(i).isNull(
										"ClientLoggedAt"))
									friendListItem
											.setClientLoggedAt(new DateEpoch(
													JsonFriendList
															.getJSONObject(i)
															.getString(
																	"ClientLoggedAt")));
								else
									friendListItem
											.setClientLoggedAt(new DateEpoch(
													"0"));
								friendListItem.setTimeSince(new DateEpoch(
										JsonFriendList.getJSONObject(i)
												.getString("TimeSince")));
								friendListR.add(friendListItem);
							}
							friendStatusR.setFriendList(friendListR);
						} catch (JSONException e1) {
							e1.printStackTrace();
						}
						setNewFriendStatus(friendStatusR);
					}
				});

		List<NameValuePair> params2 = new ArrayList<NameValuePair>();
		params2.add(new BasicNameValuePair("Token", LoginActivity.Token));

		params2.add(new BasicNameValuePair("Latitude", Double
				.toString(currentLocation.getLatitude())));
		params2.add(new BasicNameValuePair("Longitude", Double
				.toString(currentLocation.getLongitude())));
		params2.add(new BasicNameValuePair("Radius", Double.toString(5)));
		params2.add(new BasicNameValuePair("Skip", Integer.toString(0)));
		params2.add(new BasicNameValuePair("Take", Integer.toString(20)));
		manager.sentRequest(
				"http://www.lamp.mn/lamp/webservices/getFriendLists.php",
				params2, new OnHttpConnectionLoad() {

					@Override
					public void onHttpConnectionFailed() {
						// TODO Auto-generated method stub

					}

					@Override
					public void onHttpConnectionExecuted(String response) {

						Log.v("LoginActivity", "GETFRIENDLIST");
						final FriendStatus friendStatus = new FriendStatus();
						final List<FriendList> friendList = new ArrayList<FriendList>();
						try {
							JSONObject JsonFriendListStatus = new JSONObject(
									response);
							friendStatus.setStatusCode(JsonFriendListStatus
									.getInt("StatusCode"));
							friendStatus.setTotal(JsonFriendListStatus
									.getInt("Total"));
							JSONArray JsonFriendList = JsonFriendListStatus
									.getJSONArray("FriendList");
							for (int i = 0; i < JsonFriendList.length(); i++) {
								FriendList friendListItem = new FriendList();
								friendListItem.setFriendId(JsonFriendList
										.getJSONObject(i).getInt("FriendId"));
								friendListItem.setUserId(JsonFriendList
										.getJSONObject(i).getInt("UserId"));
								friendListItem
										.setUserName(JsonFriendList
												.getJSONObject(i).getString(
														"UserName"));
								friendListItem.setAddress(JsonFriendList
										.getJSONObject(i).getString("Address"));
								friendListItem.setPhoto(JsonFriendList
										.getJSONObject(i).getString("Photo"));
								friendListItem.setMutualFriend(JsonFriendList
										.getJSONObject(i)
										.getInt("MutualFriend"));
								friendListItem.setLoggedAt(new DateEpoch(
										JsonFriendList.getJSONObject(i)
												.getString("LoggedAt")));
								if (!JsonFriendList.getJSONObject(i).isNull(
										"ClientLoggedAt"))
									friendListItem
											.setClientLoggedAt(new DateEpoch(
													JsonFriendList
															.getJSONObject(i)
															.getString(
																	"ClientLoggedAt")));
								else
									friendListItem
											.setClientLoggedAt(new DateEpoch(
													"0"));
								friendListItem.setTimeSince(new DateEpoch(
										JsonFriendList.getJSONObject(i)
												.getString("TimeSince")));
								friendListItem
										.setLastSeen(JsonFriendList
												.getJSONObject(i).getString(
														"LastSeen"));
								friendListItem.setLastSeenTime(new DateEpoch(
										JsonFriendList.getJSONObject(i)
												.getString("LastSeenTime")));
								if (!JsonFriendList.getJSONObject(i).isNull(
										"LastSeenId")
										&& !JsonFriendList.getJSONObject(i)
												.getString("LastSeenId")
												.equals(""))
									friendListItem.setLastSeenId(JsonFriendList
											.getJSONObject(i).getInt(
													"LastSeenId"));
								else
									friendListItem.setLastSeenId(0);
								if (!JsonFriendList.getJSONObject(i).isNull(
										"Latitude")
										&& !JsonFriendList.getJSONObject(i)
												.getString("Latitude")
												.equals(""))
									friendListItem.setLatitude(JsonFriendList
											.getJSONObject(i).getDouble(
													"Latitude"));
								if (!JsonFriendList.getJSONObject(i).isNull(
										"Longitude")
										&& !JsonFriendList.getJSONObject(i)
												.getString("Longitude")
												.equals(""))
									friendListItem.setLongitude(JsonFriendList
											.getJSONObject(i).getDouble(
													"Longitude"));
								friendList.add(friendListItem);
							}
							friendStatus.setFriendList(friendList);
						} catch (JSONException e1) {
							e1.printStackTrace();
						}
						setFriendStatus(friendStatus);

					}
				});

		List<NameValuePair> params3 = new ArrayList<NameValuePair>();
		params3.add(new BasicNameValuePair("Token", LoginActivity.Token));
		params3.add(new BasicNameValuePair("Skip", Integer.toString(0)));
		params3.add(new BasicNameValuePair("Take", Integer.toString(20)));
		manager.sentRequest(
				"http://www.lamp.mn/lamp/webservices/getMessageLists.php",
				params3, new OnHttpConnectionLoad() {

					@Override
					public void onHttpConnectionFailed() {
						// TODO Auto-generated method stub

					}

					@Override
					public void onHttpConnectionExecuted(String response) {
						final MessageListStatus messageListStatus = new MessageListStatus();
						final List<MessageList> messageList = new ArrayList<MessageList>();
						int newSms = 0;

						Log.v("LoginActivity", "GETMESSAGELIST");
						try {
							JSONObject JsonMessageListStatus = new JSONObject(
									response);
							messageListStatus
									.setStatusCode(JsonMessageListStatus
											.getInt("StatusCode"));
							messageListStatus.setTotal(JsonMessageListStatus
									.getInt("Total"));
							JSONArray JsonMessages = JsonMessageListStatus
									.getJSONArray("MessageList");
							for (int i = 0; i < JsonMessages.length(); i++) {
								MessageList message = new MessageList();
								message.setMessageId(JsonMessages
										.getJSONObject(i).getInt("MessageId"));
								message.setMessageCode(JsonMessages
										.getJSONObject(i).getString(
												"MessageCode"));
								if (JsonMessages.getJSONObject(i).has("UserId"))
									message.setUserId(JsonMessages
											.getJSONObject(i).getInt("UserId"));
								message.setUserName(JsonMessages.getJSONObject(
										i).getString("UserName"));
								message.setUserNames(JsonMessages
										.getJSONObject(i)
										.getString("UserNames"));
								message.setStatusNew(JsonMessages
										.getJSONObject(i).getBoolean(
												"StatusNew"));
								if (message.getStatusNew())
									newSms = newSms + 1;
								message.setPhoto(JsonMessages.getJSONObject(i)
										.getString("Photo"));
								message.setNote(JsonMessages.getJSONObject(i)
										.getString("Note"));
								message.setLoggedAt(new DateEpoch(JsonMessages
										.getJSONObject(i).getString("LoggedAt")));
								message.setTimeSince(new DateEpoch(JsonMessages
										.getJSONObject(i)
										.getString("TimeSince")));
								messageList.add(message);

							}
							messageListStatus.setMessageList(messageList);
						} catch (JSONException e1) {
							e1.printStackTrace();
						}
						final int sms = newSms;
						dialog.dismiss();
						setNewMessageTotal(sms);
						setMessageListStatus(messageListStatus);
						Intent intent = new Intent();
						intent.setClass(LoginActivity.this,
								TabBarActivity.class);
						startActivity(intent);

					}
				});

	}

	public void removeFriends(int userId) {
		for (FriendList k : newFriendStatus.getFriendList()) {
			if (k.getUserId() == userId) {
				friendStatus.getFriendList().add(0, k);
				friendStatus.setTotal(friendStatus.getTotal() + 1);
				newFriendStatus.getFriendList().remove(k);
				newFriendStatus.setTotal(newFriendStatus.getTotal() - 1);
				break;
			}

		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		Log.d("keyboard", "No");
		if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
			Log.d("keyboard", "No");
		} else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
			Log.d("keyboard", "Yes");
		}
	}

	public void onLocationChanged(Location paramLocation) {
		// TODO Auto-generated method stub

	}

	public void onStatusChanged(String paramString, int paramInt,
			Bundle paramBundle) {
		// TODO Auto-generated method stub

	}

	public void onProviderEnabled(String paramString) {
		// TODO Auto-generated method stub

	}

	public void onProviderDisabled(String paramString) {
		// TODO Auto-generated method stub

	}
}